from Ling.common.utils.OcrUtils import get_txt_from_reader_file, get_txt_from_reader_file_check
from Ling.common.utils.StringUtils import clear_str
from Ling.paddle.ocr.dao.ReaderDao import fetch_all_books, fetch_all_book_chapters


# '国医大师专科专病用方经验（第2辑）：肿瘤病分册'
def scan_336_books_2_root_folder(reader_root, out_root):
    books = fetch_all_books('336')
    with open('D:/ocr/ocr_resouces/reader/all_path.txt', 'w', encoding='utf-8') as aw:
        with open('D:/ocr/ocr_resouces/reader/all_loss_path.txt', 'w', encoding='utf-8') as loss:
            for book in books:
                name = book['name']
                name = clear_str(name)
                reader_id = book['i_reader_id']
                # print(name + '-->' + name + '-->' + reader_id)
                chapters = fetch_all_book_chapters(reader_id)
                chapter_texts = []
                for chapter in chapters:
                    chapter_path = chapter['path']
                    if chapter_path is not None:
                        aw.write(chapter_path + '\n')
                        if chapter_path is not None:
                            path = reader_root + chapter_path
                            exits, texts = get_txt_from_reader_file(path)
                            if exits:
                                chapter_texts = chapter_texts + texts
                            else:
                                loss.write(chapter_path + '\n')
                out_path = out_root + reader_id + '~' + name + '_content.txt'
                with open(out_path, 'w', encoding='utf-8') as w:
                    for line in chapter_texts:
                        w.write(line + '\n')


def scan_336_books_2_root_folder_check(reader_root, out_root):
    books = fetch_all_books('336')
    folders = []
    for book in books:
        name = book['name']
        name = clear_str(name)
        reader_id = book['i_reader_id']
        # print(name + '-->' + name + '-->' + reader_id)

        chapters = fetch_all_book_chapters(reader_id)

        for chapter in chapters:
            chapter_path = chapter['path']
            if chapter_path is not None:
                path = reader_root + chapter_path
                exists = get_txt_from_reader_file_check(path)
                if not exists:
                    folders.append(chapter_path)
                    # break
    with open('D:/ocr/ocr_resouces/reader/all_loss_path.txt', 'w', encoding='utf-8') as w:
        for folder in folders:
            w.write(folder + "\n")


scan_336_books_2_root_folder('E:/books/oss_local/', 'D:/ocr/ocr_resouces/reader/')
# scan_336_books_2_root_folder_check('E:/books/oss_local/', 'D:/ocr/ocr_resouces/reader/')

# folder = 'D:/ocr/ocr_resouces/reader/folder/cha.html'.split('/')
# print()
